package com.itheima.health.mobile.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @author ：seanyang
 * @date ：Created in 2019/6/13
 * @description ：登录Servlet
 * @version: 1.0
 */
@RestController
@RequestMapping("/mobile/login")
public class LoginController {

	@Autowired
	private JedisPool jedisPool;

	@Reference
	private MemberService memberService;

	/**
	 * 短信登录
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping("/smsLogin")
	public Result smsLogin(HttpServletResponse response, @RequestBody Map<String,String> map){
		// 获取客户端数据
		String telephone = map.get("telephone");
		String validateCode = map.get("validateCode");
		// 从redis读取验证码
		String codeInRedis = jedisPool.getResource().get(telephone+ RedisConst.SENDTYPE_LOGIN);
		if( codeInRedis == null || !codeInRedis.equals(validateCode)){
			// 验证码错误
			return new Result(false, MessageConst.VALIDATECODE_ERROR);
		}
		// 检查是否是会员
		Member member = memberService.findByTelephone(telephone);
		if (member == null){
			member = new Member();
			member.setPhoneNumber(telephone);
			member.setRegTime(new Date());
			memberService.add(member);
		}
		// 存储cookie到客户端
		Cookie cookie = new Cookie("login_member_telephone",telephone);
		cookie.setPath("/");
		cookie.setMaxAge(60*5);
		response.addCookie(cookie);

		return new Result(true,MessageConst.LOGIN_SUCCESS);
	}
}
